<?php

/**
 * String Class
 * @author ReGeDa
 */
class String extends Plugin_Object {

	/**
	 * Random string
	 * @staticvar resource $f
	 * @param string $type
	 * @param integer $len
	 * @return string 
	 */
	public static function random($type = 'alpha', $len = 8) {

		switch($type) {
			//------------------------------------------------------------------
			case 'raw':
				static $f = NULL;

				if ($f === NULL)
					$f = @fopen('/dev/urandom', 'r');

				return fread($f, $len);
			//------------------------------------------------------------------
			case 'alnum': $pool = '0123456789';
			case 'alpha': $pool .= 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; break;
			//------------------------------------------------------------------
			case 'numeric':
				$n = mt_rand(1,9);
				for($i = 1; $i < $len; $i++)
					$n .= mt_rand(0,9);
				return $n;
			//------------------------------------------------------------------
			case 'unique' :
				return md5(uniqid(mt_rand()));
			//------------------------------------------------------------------
			default:
				return FALSE;
		}
		// Post processing
		// Generate random string from pool
		$str = '';
		for ($i = 0, $count = strlen($pool) - 1; $i < $len; $i++)
			$str .= substr($pool, mt_rand(0, $count), 1);
		// Result
		return $str;
	}

	/**
	 * Calculate a password strength
	 * @param string $value
	 * @return integer
	 */
	public static function pass_strength($value) {
		$length = mb_strlen($value,'UTF-8');

		// check length
		if ($length) {

			$n = 0;

			// calculate string length
			if ($length > 2 && $length < 5)
				$n += 15;
			else if ($length > 4 && $length < 7)
				$n += 25;
			else if ($length > 6)
				$n += 40;

			// calculate string content
			if ($length > 4) {
				if (preg_match('/[a-zA-Z]/', $value))
					$n += 10;
				if (preg_match('/([a-z].*[A-Z])|([A-Z].*[a-z])/', $value))
					$n += 25;
				if (preg_match('/([^\d]+\d+)+/', $value))
					$n += 25;
				if (preg_match('/[^a-zA-Z\d]+/', $value))
					$n += 15;
			}

			// select a level
			if ($n < 26) return 1; // very bad
			if ($n > 25 && $n < 46) return 2; // bad
			if ($n > 45 && $n < 66) return 3; // good
			if ($n > 65 && $n < 86) return 4; // very good

			return 5; // excellent
		}
		// empty password
		return 0;
	}
}

// end of file